﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json;
using Sunlight.Dispatch.Dal;
using Sunlight.Dispatch.Model;
using Sunlight.Dispatch.Tools;
using Sunlight.Dispatch.UI.Controls;
using Sunlight.Dispatch.UI.Properties;

namespace Sunlight.Dispatch.UI {
    public partial class FileLogInformationFrm : BaseFrm {
        private readonly List<KeyValueItem> dispatchStatus = new List<KeyValueItem>();
        public FileLogInformationFrm() {
            InitializeComponent();
            this.Load += InterfaceLogFrm_Load;
        }

        private void InterfaceLogFrm_Load(object sender, EventArgs e) {
            var keyValueItems = JsonConvert.DeserializeObject<List<KeyValueItem>>(Settings.Default.SendStatus);
            this.cmbSendStatus.DataSource = keyValueItems;
            this.cmbSendStatus.DisplayMember = "Value";
            this.cmbSendStatus.ValueMember = "Key";
            dispatchStatus.Clear();
            dispatchStatus.AddRange(keyValueItems);

            this.dtpDateBegin.Value = DateTime.Now.AddDays(-7);
            this.dtpTimeBegin.Value = DateTime.Now.ToStartEarlyMorning();
            this.dtpTimeEnd.Value = DateTime.Now.ToEndEarlyMorning();

            this.pagerControl.OnPageChanged += this.PagerControl_OnPageChanged;
            this.OnControlCreated(this.dgvLogInfo, this.pagerControl);
            this.pagerControl.PageSize = 100;
            this.btnSearch.Click -= this.btnSearch_Click;
            this.btnSearch.Click += this.btnSearch_Click;
            this.txbSysCode.KeyDown += TxbCommon_KeyDown;
            this.txbSysCode.KeyDown += TxbCommon_KeyDown;
            this.txbKeyWords.KeyDown += TxbCommon_KeyDown;

            this.InitComboBoxForDataBase(this.comboBoxDataBase);
        }

        private void TxbCommon_KeyDown(object sender, KeyEventArgs e) {
            if(e.KeyCode == Keys.Enter)
                this.SearchGridView(1);
        }

        protected override void LoadInitLocation() {
            base.LoadInitLocation();
            this.dgvLogInfo.Height = this.Height - this.gbCondition.Height - this.pageControlPanel.Height - 70;
            this.dgvLogInfo.Width = this.Width - 50;
            this.dgvLogInfo.ScrollBars = ScrollBars.Vertical;
            this.pageControlPanel.Location = new Point(this.dgvLogInfo.Location.X, this.dgvLogInfo.Location.Y + this.dgvLogInfo.Height);
            this.pageControlPanel.Width = this.dgvLogInfo.Width;
            var locationX = this.dgvLogInfo.Width - this.pagerControl.Width - 50;
            this.pagerControl.Location = new Point(this.pageControlPanel.Location.X + locationX, pagerControl.Location.Y);
        }

        private void PagerControl_OnPageChanged(object sender, PageControlEvemtArgs e) {
            this.SearchGridView(e.PageIndex);
        }

        private void btnSearch_Click(object sender, EventArgs e) {
            SearchGridView(1);
        }

        private void SearchGridView(int pageIndex) {
            this.IsLoading = true;
            if(this.comboBoxDataBase.SelectedItem == null) {
                MessageBoxEx.Show(this, "请选择数据库", "提示");
                return;
            }
            var db = this.comboBoxDataBase.SelectedItem as ConnectStringConfigTb;
            if(db == null)
                return;
            using(var dataContext = new MonitorSettingDataContext(db.ConnectString)) {
                IQueryable<TFileLog> tlog = dataContext.TFileLog;
                IQueryable<TIntf> tinf = dataContext.TIntf;
                IQueryable<TBusiness> business = dataContext.TBusiness;
                var result = from log in tlog
                             join inf in tinf on log.IntfCode equals inf.Code into temp
                             from inf in temp.DefaultIfEmpty()
                             join bus in business on log.BusinessCode equals bus.Code into temp1
                             from bus in temp1.DefaultIfEmpty()
                             select new {
                                 log,
                                 inf,
                                 bus
                             };

                var methodName = this.txbMethod.Text;
                var sysCode = this.txbSysCode.Text;
                var keyWords = this.txbKeyWords.Text;
                var dispachStatus = this.cmbSendStatus.SelectedValue as int?;
                var dateBegin = this.dtpDateBegin.Value.ToStartEarlyMorning();
                var dateEnd = this.dtpDateEnd.Value.ToEndEarlyMorning();
                var timeBegin = this.dtpTimeBegin.Value.ToStartEarlyMorning();
                var timeEnd = this.dtpTimeEnd.Value.ToEndEarlyMorning();

                var dateDownloadBegin = this.dtpDateDownloadBegin.Value.ToStartEarlyMorning();
                var dateDownloadEnd = this.dtpDateDownloadEnd.Value.ToEndEarlyMorning();
                var timeDownloadBegin = this.dtpTimeDownloadBegin.Value.ToStartEarlyMorning();
                var timeDownloadEnd = this.dtpTimeDownloadEnd.Value.ToEndEarlyMorning();
                var businessCode = this.txbBusinessCode.Text;
                var businessName = this.txbBusinessName.Text;
                var infoCode = this.txbInfoCode.Text;
                var infoName = this.txbInfoName.Text;

                if(!string.IsNullOrEmpty(methodName)) {
                    result = result.Where(d => d.inf.UpFunction.ToLower().Contains(methodName.ToLower()));
                }
                if(!string.IsNullOrEmpty(sysCode)) {
                    result = result.Where(d => d.log.SysCode.ToLower().Contains(sysCode.ToLower()));
                }
                if(!string.IsNullOrEmpty(businessCode)) {
                    result = result.Where(d => d.log.BusinessCode.ToLower().Contains(businessCode.ToLower()));
                }
                if(!string.IsNullOrEmpty(businessName)) {
                    result = result.Where(d => d.bus.Name.ToLower().Contains(businessName.ToLower()));
                }
                if(!string.IsNullOrEmpty(infoCode)) {
                    result = result.Where(d => d.inf.Code.ToLower().Contains(infoCode.ToLower()));
                }
                if(!string.IsNullOrEmpty(infoName)) {
                    result = result.Where(d => d.inf.Name.ToLower().Contains(infoName.ToLower()));
                }
                if(!string.IsNullOrEmpty(keyWords)) {
                    result = result.Where(d => d.inf.UpFunction.ToLower().Contains(keyWords.ToLower())
                                               || d.inf.Code.ToLower().Contains(keyWords.ToLower())
                                               || d.inf.Name.ToLower().Contains(keyWords.ToLower())
                                               || d.inf.Uper.ToLower().Contains(keyWords.ToLower())
                                               || d.inf.DownFunction.ToLower().Contains(keyWords.ToLower())
                                               || d.inf.Downer.ToLower().Contains(keyWords.ToLower())
                                               || d.inf.BusinessCode.ToLower().Contains(keyWords.ToLower())
                                               || d.inf.CompleteMethod.ToLower().Contains(keyWords.ToLower())
                                               || d.log.FileDir.ToLower().Contains(keyWords.ToLower())
                                               || d.log.BusinessCode.ToLower().Contains(keyWords.ToLower())
                                               || d.log.SysCode.ToLower().Contains(keyWords.ToLower())
                                               || d.bus.Code.ToLower().Contains(keyWords.ToLower())
                                               || d.bus.Name.ToLower().Contains(keyWords.ToLower()));
                }

                if(dispachStatus != -1) {
                    result = result.Where(d => d.log.Status == dispachStatus);
                }

                if(!cbIsClearDateCondition.Checked) {
                    result = result.Where(d => d.log.UpTime >= dateBegin);
                    result = result.Where(d => d.log.UpTime <= dateEnd);
                    var timeBeginMinute = timeBegin.Hour * 60 + timeBegin.Minute;
                    result = result.Where(d => d.log.UpTime.HasValue && d.log.UpTime.Value.Hour * 60 + d.log.UpTime.Value.Minute >= timeBeginMinute);
                    var timeEndMinute = timeEnd.Hour * 60 + timeEnd.Minute;
                    result = result.Where(d => d.log.UpTime.HasValue && d.log.UpTime.Value.Hour * 60 + d.log.UpTime.Value.Minute <= timeEndMinute);

                    result = result.Where(d => d.log.DownTime >= dateDownloadBegin);
                    result = result.Where(d => d.log.DownTime <= dateDownloadEnd);
                    var timeDownloadBeginMinute = timeBegin.Hour * 60 + timeBegin.Minute;
                    result = result.Where(d => d.log.DownTime.HasValue && d.log.DownTime.Value.Hour * 60 + d.log.DownTime.Value.Minute >= timeDownloadBeginMinute);
                    var timeDownloadEndMinute = timeEnd.Hour * 60 + timeEnd.Minute;
                    result = result.Where(d => d.log.DownTime.HasValue && d.log.DownTime.Value.Hour * 60 + d.log.DownTime.Value.Minute <= timeDownloadEndMinute);
                }

                var recordCount = result.Count();
                var data = result.OrderByDescending(d => d.log.ID).Skip((pageIndex - 1) * this.pagerControl.PageSize).Take(this.pagerControl.PageSize).Select(
                    d => new FileLogViewModel {
                        Id = d.log.ID,
                        BusinessCode = d.log.BusinessCode,
                        BusinessName = d.bus.Name,
                        InfoCode = d.inf.Code,
                        InfoName = d.inf.Name,
                        UpFunction = d.inf.UpFunction,
                        DownFunction = d.inf.DownFunction,
                        Uper = d.inf.Uper,
                        Downer = d.inf.Downer,
                        MaxNum = d.inf.MaxNum,
                        Memo = d.inf.Memo,
                        ThreadNum = d.inf.ThreadNum,
                        FileName = d.log.FileName,
                        FileDir = d.log.FileDir,
                        UpTime = d.log.UpTime,
                        DownTime = d.log.DownTime,
                        Status = d.log.Status,
                        ConnectString = db.ConnectString
                    }).ToList();
                data.ForEach(d => {
                    var item = dispatchStatus.FirstOrDefault(keyValue => keyValue.Key == d.Status);
                    if(item != null)
                        d.SendStatus = item.Value;
                });
                this.dgvLogInfo.DataSource = data;
                this.pagerControl.PageIndex = pageIndex;
                this.pagerControl.DrawControl(recordCount);
                this.IsLoading = false;
            }
        }
    }
}
